<template>
  <el-popover
    v-model="visible"
    :popper-class="!token && onlyLange ? 'only-lange-popover' : 'lange-popover'"
    placement="bottom"
    trigger="click"
    @show="popoverShow"
    @hide="popoverHide"
  >
    <el-scrollbar class="scroll-list" v-if="!token && onlyLange">
      <div
        :class="['scroll-item', curCountry.language_code == key ? 'active' : '']"
        v-for="(val, key, index) in languageObj"
        :key="index"
        @click="selectChange(key)"
      ></div>
    </el-scrollbar>
    <!-- 国家 -->
    <!-- 国家 -->
    <!-- 国家 -->
    <div class="lange-card" v-else>
      <div class="item-row">
        <div class="label">{{ $t('formItem.countryRegion') }}</div>
        <div class="select flexbox flex-align-center">
          <!-- <LazyCountrySelect
            class="input"
            :targetCountry="userSelectInfo"
            @itemChange="countryChange"
          /> -->
        </div>
      </div>
      <!-- 语言 -->
      <!-- 语言 -->
      <!-- 语言 -->
      <div class="item-row">
        <div class="label">{{ $t('formItem.lange') }}</div>
        <div class="select flexbox flex-align-center">
          <LangesSelect class="input" :isSetData="false" :languageCode="curCountry.language_code" @itemChange="languageChange" />
        </div>
      </div>
      <!-- 货币 -->
      <!-- 货币 -->
      <!-- 货币 -->
      <div class="item-row">
        <div class="label">{{ $t('formItem.currency') }}</div>
        <div class="select flexbox flex-align-center">
          <el-select class="input" filterable v-model="curCountry.currency_code" :placeholder="$t('formPlaceholder.select')">
            <template slot="prefix">
              <img
                class="icon"
                src="https://cd.sealmg.com/assets/img/set-plane-currency.png"
                alt="https://cd.sealmg.com/assets/img/set-plane-currency.png"
                srcset=""
                loading="lazy"
              />
            </template>
            <el-option v-for="(item, index) in currencyList" :key="index" :label="item.currency_name" :value="item.currency_code"> </el-option>
          </el-select>
        </div>
      </div>
      <div class="handle">
        <el-button class="theme-btn" @click="sureSelect"> {{ $t('formBtn.confirm') }}</el-button>
      </div>
    </div>
    <div slot="reference" class="lange-btn lange-border-btn flexbox flex items-center justify-center" v-if="langTheme == 'border'">
      <img
        class="icon"
        v-if="!userSelectInfo.country_icon || onlyLange"
        src="https://cd.sealmg.com/assets/img/mobile/lang-icon.png"
        alt="https://cd.sealmg.com/assets/img/mobile/lang-icon.png"
        srcset=""
        loading="lazy"
      />
      <img
        class="icon"
        v-if="userSelectInfo.country_icon && !onlyLange"
        v-lazy="$globalFn.imgPrefixUrl(userSelectInfo.country_icon)"
        :alt="userSelectInfo.country_icon"
        srcset=""
        loading="lazy"
      />
      <span class="text">{{ toUpperCase(userSelectInfo.country_code) }}</span>
      <template v-if="showArrow">
        <img
          :class="['arrow', visible ? 'arrow-hide' : '']"
          src="https://cd.sealmg.com/assets/img/show-open-icon.png"
          alt="https://cd.sealmg.com/assets/img/show-open-icon.png"
          srcset=""
          loading="lazy"
        />
      </template>
    </div>
    <div slot="reference" class="lange-btn lange-transparent-btn flexbox flex items-center justify-center" v-if="langTheme == 'transparent'">
      <img
        class="icon"
        v-if="!userSelectInfo.country_icon || onlyLange"
        src="https://cd.sealmg.com/assets/img/mobile/lang-icon.png"
        alt="https://cd.sealmg.com/assets/img/mobile/lang-icon.png"
        srcset=""
        loading="lazy"
      />
      <img
        class="icon"
        v-if="userSelectInfo.country_icon && !onlyLange"
        v-lazy="$globalFn.imgPrefixUrl(userSelectInfo.country_icon)"
        :alt="userSelectInfo.country_icon"
        srcset=""
        loading="lazy"
      />
      <span class="text">{{ toUpperCase(userSelectInfo.country_code) }}</span>
      <template v-if="showArrow">
        <img
          :class="['arrow', visible ? 'arrow-hide' : '']"
          src="https://cd.sealmg.com/assets/img/mobile/show-open-icon.png"
          alt="https://cd.sealmg.com/assets/img/mobile/show-open-icon.png"
          srcset=""
          loading="lazy"
        />
      </template>
    </div>
    <!--  -->
    <!--  -->
    <!--  -->
    <div slot="reference" class="lange-btn lange-gray-btn flexbox flex items-center justify-center" v-if="langTheme == 'gray'">
      <img
        class="icon"
        v-if="!userSelectInfo.country_icon || onlyLange"
        src="https://cd.sealmg.com/assets/img/mobile/lang-icon.png"
        alt="https://cd.sealmg.com/assets/img/mobile/lang-icon.png"
        srcset=""
        loading="lazy"
      />
      <img
        class="icon"
        v-if="userSelectInfo.country_icon && !onlyLange"
        v-lazy="$globalFn.imgPrefixUrl(userSelectInfo.country_icon, 'national_flag')"
        :alt="userSelectInfo.country_icon"
        srcset=""
        loading="lazy"
      />
      <span class="text">{{ toUpperCase(userSelectInfo.country_code) }}</span>
      <template v-if="showArrow">
        <img
          :class="['arrow', visible ? 'arrow-hide' : '']"
          src="https://cd.sealmg.com/assets/img/mobile/show-open-icon.png"
          alt="https://cd.sealmg.com/assets/img/mobile/show-open-icon.png"
          srcset=""
          loading="lazy"
        />
      </template>
    </div>
    <div slot="reference" class="lange-btn lange-gray-btn flexbox flex items-center justify-center" v-if="langTheme == 'gray2'">
      <img
        class="icon"
        v-if="!userSelectInfo.country_icon || onlyLange"
        src="https://cd.sealmg.com/assets/img/mobile/lang-icon.png"
        alt="https://cd.sealmg.com/assets/img/mobile/lang-icon.png"
        srcset=""
        loading="lazy"
      />
      <img
        class="icon"
        v-if="userSelectInfo.country_icon && !onlyLange"
        v-lazy="$globalFn.imgPrefixUrl(userSelectInfo.country_icon)"
        :alt="userSelectInfo.country_icon"
        srcset=""
      />
      <span class="text">{{ toUpperCase(userSelectInfo.country_code) }}</span>
      <template v-if="showArrow">
        <img
          :class="['arrow', visible ? 'arrow-hide' : '']"
          src="https://cd.sealmg.com/assets/img/show-open-icon.png"
          alt="https://cd.sealmg.com/assets/img/show-open-icon.png"
          srcset=""
          loading="lazy"
        />
      </template>
    </div>
    <div slot="reference" class="lange-btn lange-white-btn flexbox flex items-center justify-center" v-if="langTheme == 'white'">
      <!-- {{ userSelectInfo.country_icon }}\\{{ onlyLange }} -->
      <img
        class="icon"
        v-if="!userSelectInfo.country_icon || onlyLange"
        src="https://cd.sealmg.com/assets/img/lang-white-icon.png"
        alt="https://cd.sealmg.com/assets/img/lang-white-icon.png"
        srcset=""
        loading="lazy"
      />
      <img
        class="icon"
        v-if="userSelectInfo.country_icon && !onlyLange"
        v-lazy="$globalFn.imgPrefixUrl(userSelectInfo.country_icon)"
        :slot="userSelectInfo.country_icon"
        srcset=""
        loading="lazy"
      />
      <span class="text">{{ toUpperCase(userSelectInfo.country_code) }}</span>
      <template v-if="showArrow">
        <img
          :class="['arrow', visible ? 'arrow-hide' : '']"
          src="https://cd.sealmg.com/assets/img/arrow-open-white.png"
          alt="https://cd.sealmg.com/assets/img/arrow-open-white.png"
          srcset=""
          loading="lazy"
        />
      </template>
    </div>
    <div slot="reference" class="lange-btn lange-white2-btn flexbox flex items-center justify-center" v-if="langTheme == 'white2'">
      <img
        class="icon"
        v-if="!userSelectInfo.country_icon || onlyLange"
        src="https://cd.sealmg.com/assets/img/mobile/lang-icon.png"
        alt="https://cd.sealmg.com/assets/img/mobile/lang-icon.png"
        srcset=""
        loading="lazy"
      />
      <img
        class="icon"
        v-if="userSelectInfo.country_icon && !onlyLange"
        v-lazy="$globalFn.imgPrefixUrl(userSelectInfo.country_icon)"
        :alt="userSelectInfo.country_icon"
        srcset=""
        loading="lazy"
      />
      <span class="text">{{ toUpperCase(userSelectInfo.country_code) }}</span>
      <template v-if="showArrow">
        <img
          :class="['arrow', visible ? 'arrow-hide' : '']"
          src="https://cd.sealmg.com/assets/img/show-open-icon.png"
          alt="https://cd.sealmg.com/assets/img/show-open-icon.png"
          srcset=""
          loading="lazy"
        />
      </template>
    </div>
  </el-popover>
</template>
<script>
  import { throttle } from '@/static/js/common'
  export default {
    // inject: ["refresh"],
    props: {
      langTheme: {
        type: String, //white
        default: 'lange-btn'
      },
      showArrow: {
        type: Boolean,
        default: true
      },
      onlyLange: {
        type: Boolean,
        default: false
      },
      form: {
        type: Object
      }
    },
    data() {
      return {
        countryList: [],
        mobile: true,
        visible: false,
        curCountry: {
          country_icon: '',
          country_code: '',
          language_code: '', //this.$i18n.locale,
          currency_code: ''
        },
        userSelectInfo: {
          country_icon: '',
          country_code: '',
          language_code: '', //this.$i18n.locale,
          currency_code: ''
        }
      }
    },
    // watch: {
    //   $route(to, from) {
    //     ;
    //     Object.assign(this.$data, this.$options.data());
    //   },
    //   "$store.state.initData.regions": {
    //     handler: function (val) {
    //       let list = [];
    //       let list2 = [];
    //       list2 = JSON.parse(JSON.stringify(val));
    //       if (list2.length) {
    //         list2.map((item) => {
    //           if (item._child && item._child.length) {
    //             list.push(...item._child);
    //           }
    //         });
    //       }
    //       this.countryList = list;
    //       this.initData();
    //       // ;
    //     },
    //   },
    // },
    watch: {
      '$store.state.initData.regions': {
        immediate: true,
        deep: true,
        handler(val) {
          let list = []
          let list2 = []
          list2 = JSON.parse(JSON.stringify(val))
          // if (list2.length) {
          //   list2.map((item) => {
          //     if (item._child && item._child.length) {
          //       list.push(...item._child);
          //     }
          //   });
          // }
          this.countryList = list //.sort((a, b) => a.name.localeCompare(b.name));
          this.initData()
          // ;
        }
      }
    },
    computed: {
      token() {
        return this.$cookies.get('token') || this.$store.state.user.token || ''
      },
      userSelect() {
        let initData = this.$store.state.initData
        return initData.userSelect || {}
      },
      // countryList() {
      //   let list = [];
      //   let list2 = [];
      //   ;
      //   if (
      //     this.$store &&
      //     this.$store.state &&
      //     this.$store.state.initData &&
      //     this.$store.state.initData.regions
      //   ) {
      //     list2 = JSON.parse(JSON.stringify(this.$store.state.initData.regions));
      //   }
      //   if (list2.length) {
      //     list2.map((item) => {
      //       if (item._child && item._child.length) {
      //         list.push(...item._child);
      //       }
      //     });
      //   }
      //   return list;
      // },
      languageObj() {
        let language = {}
        if (this.$store && this.$store.state && this.$store.state.initData && this.$store.state.initData.language) {
          language = JSON.parse(JSON.stringify(this.$store.state.initData.language))
        }
        return language
      },
      currencyList() {
        let currencies = {}
        let list = []
        if (this.$store && this.$store.state && this.$store.state.initData && this.$store.state.initData.currencies) {
          currencies = JSON.parse(JSON.stringify(this.$store.state.initData.currencies))
        }
        if (currencies) {
          list = Object.values(currencies)
        }
        return list
      }
    },
    created() {
      // setTimeout(() => {
      //   ;
      //
      // }, 2000);
    },
    methods: {
      initData() {
        let userSelect = this.$cookies.get('userSelect')
        if (userSelect && userSelect.country_code) {
          this.userSelectInfo = userSelect
          if (!userSelect.country_icon) {
            let list2 = []
            list2 = this.countryList.filter(item => item.iso == this.userSelectInfo.country_code)
            //
            if (list2.length) {
              this.userSelectInfo['country_icon'] = list2[0].icon
            }
          }
        }
      },
      popoverShow() {
        let userSelect = this.$cookies.get('userSelect')
        this.curCountry = JSON.parse(JSON.stringify(this.userSelectInfo))
        this.curCountry.language_code = userSelect.language_code
      },
      popoverHide() {
        this.curCountry = {}
      },
      toUpperCase(val) {
        if (val && typeof val == 'string') {
          let text = JSON.parse(JSON.stringify(val))
          return text.toUpperCase()
        } else {
          return val
        }
      },
      countryChange(item) {
        this.curCountry.country_icon = item.icon || ''
        this.curCountry.country_code = item.iso || item.country_code
        this.curCountry.language_code = item.language_code
        this.curCountry.currency_code = item.currency_code
      },
      selectChange(val) {
        this.curCountry.language_code = val
        this.sureSelect()
      },
      languageChange(val) {
        this.curCountry.language_code = val
      },
      sureSelect: throttle(
        function () {
          let opts = this.curCountry.country_code ? JSON.parse(JSON.stringify(this.curCountry)) : JSON.parse(JSON.stringify(this.userSelectInfo))
          if (this.token) {
            this.$axios
              .post(`/api/user/select`, opts)
              .then(res => {
                // 设置选中到缓存
                this.$store.commit('initData/setUserSelect', opts)
                // 获取最新的分类
                this.$store.dispatch('initData/getCategoryData')
                // 获取最新的底部
                this.$store.dispatch('initData/getFooterData')
                // 设置当前语言
                this.$i18n.setLocale(opts.language_code)
                // fullPath 的前缀不是包含locales  就去掉
                // if (!locales.includes(fullPath.split("/")[1])) {
                // }
                this.switchLocalePath(opts.language_code)
                // const locales = [
                //   "/ar",
                //   "/de",
                //   "/es",
                //   "/fr",
                //   "/hi",
                //   "/id",
                //   "/it",
                //   "/ja",
                //   "/ko",
                //   "/ms",
                //   "/my",
                //   "/nl",
                //   "/pt",
                //   "/ro",
                //   "/ru",
                //   "/th",
                //   "/tl",
                //   "/vi",
                //   "/zh-tw",
                //   "/zh",
                // ];
                // // 遍历语言前缀列表
                // let urls = "";
                // for (const locale of locales) {
                //   if (path.startsWith(locale)) {
                //     urls = this.$route.path.slice(locale.length); // 移除匹配的语言前缀
                //   }
                // }
                // let d = {
                //   path: urls,
                //   query: this.$route.query,
                // };
                this.visible = false
                // this.localePath(d);
                //this.$store.dispatch('initData/getInitData')
                // if (process.client) {
                //   setTimeout(() => {
                //     window.location.reload();
                //   }, 500);
                // }
              })
              .catch(err => {})
          } else {
            // 设置选中到缓存
            this.$store.commit('initData/setUserSelect', opts)
            // 获取最新的分类
            this.$store.dispatch('initData/getCategoryData')
            // 获取最新的底部
            this.$store.dispatch('initData/getFooterData')
            // 设置当前语言
            this.$i18n.setLocale(opts.language_code)
            let d = {
              path: this.$route.path,
              query: this.$route.query
            }
            this.visible = false
            this.localePath(d)
            // 写个延迟
          }
        },
        2000,
        {
          leading: true,
          trailing: false
        }
      )
    }
  }
</script>
<style lang="less" scoped>
  /deep/ .el-select .el-input .el-input__inner {
    font-size: 14px;
  }
  .lange-btn {
    padding: 0 12px;
    height: 32px;
    cursor: pointer;
    box-sizing: border-box;
    border-radius: 16px;
    .text {
      font-weight: 500;
      font-size: 12px;
      color: @font-color-26;
    }
    .arrow {
      width: 16px;
      height: 16px;
      margin-left: 4px;
    }
    .arrow-hide {
      transform: rotate(180deg);
    }
    .lang-pc {
      display: block;
    }
    .lang-mobile {
      display: none;
    }
  }
  .lange-border-btn {
    border: @border-1-f7;
    .icon {
      width: 16px;
      height: 16px;
      margin-right: 5px;
      border-radius: 50%;
    }
    .arrow {
      width: 12px;
      height: 12px;
      margin-left: 6px;
    }
  }
  .lange-transparent-btn {
    background: transparent;
    .icon {
      width: 20px;
      height: 20px;
      margin-right: 6px;
      border-radius: 50%;
    }
  }
  .lange-gray-btn {
    // margin-left: 16px;
    background: @color-f7;
    .icon {
      width: 18px;
      height: 18px;
      margin-right: 7px;
      border-radius: 50%;
    }
  }
  .lange-white-btn {
    background: rgba(255, 255, 255, 0.32);
    .icon {
      width: 20px;
      height: 20px;
      margin-right: 6px;
      border-radius: 50%;
    }
    .text {
      color: @color-ff;
    }
  }
  .lange-white2-btn {
    background: @color-ff;
    .icon {
      width: 20px;
      height: 20px;
      margin-right: 6px;
      border-radius: 50%;
    }
    .text {
      color: @font-color-26;
    }
  }
  .lange-popover {
    .lange-btn {
      .arrow {
        width: 12px;
        height: 12px;
      }
    }
    .lange-card {
      .item-row {
        margin-bottom: 16px;
        .label {
          margin-bottom: 6px;
          font-weight: 500;
          font-size: 12px;
          color: @font-color-99;
        }
        .select {
          height: 48px;
          background: @color-f7;
          border-radius: 8px;
          .icon {
            width: 24px;
            height: 24px;
            margin-top: 8px;
          }
          .input {
            flex: 1;
          }
          /deep/.el-input__inner {
            height: 48px;
            line-height: 48px;
          }
          /deep/.el-input__prefix {
            .icon {
              margin-top: 12px;
            }
          }
        }
      }
      .handle {
        padding: 8px 0 4px 0;
        .theme-btn {
          width: 100%;
          height: 50px;
          line-height: 50px;
        }
      }
    }
  }
  @media only screen and (min-width: 1200px) {
  }
  @media screen and (max-width: 992px) and (min-width: 768px) {
    .btn {
      margin-right: 8px;
      .text {
        color: @font-color-26;
      }
    }
    .lange-btn {
      padding: 0 8px;
      margin-left: 0;
      background: @color-ff;
      border: @border-1-f7;
      .icon {
        width: 14px;
        height: 14px;
        margin-right: 6px;
        border-radius: 50%;
      }
      .lang-pc {
        display: none;
      }
      .lang-mobile {
        display: block;
      }
    }
  }
  @media screen and (max-width: 767px) {
    .btn {
      margin-right: 8px;
      .text {
        color: @font-color-26;
      }
    }
    .lange-btn {
      padding: 0 8px;
      margin-left: 0;
      background: @color-ff;
      border: @border-1-f7;
      .icon {
        width: 14px;
        height: 14px;
        margin-right: 6px;
        border-radius: 50%;
      }
      .lang-pc {
        display: none;
      }
      .lang-mobile {
        display: block;
      }
    }
  }
</style>
